//
//  StockTimeLineView.m
//  K线图自治
//
//  Created by LK-IOS on 2017/12/11.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "StockTimeLineView.h"
#import "StockLinePointModel.h"
#import "UIBezierPath+StockDraw.h"
#import "UIView+StockViewExtension.h"
#import "UIColor+StockColorEntension.h"
#import "StockConst.h"

@interface StockTimeLineView()

/**
 当前绘制在屏幕上的数据源数组
 */
@property (nonatomic, strong) NSArray <__kindof StockTimeLineModel*>*timeLineModels;


/**
 分时线
 */
@property (nonatomic,strong) CAShapeLayer *lineChartLayer;

/**
 分时图边框
 */
@property (nonatomic,strong) CAShapeLayer *boxLayer;

/**
 当前选择的模型索引
 */
@property (nonatomic,assign) NSInteger curentModelIndex;

/**
 显示时间的图层
 */
@property (nonatomic,strong) CAShapeLayer *timeLayer;

/**
 显示限制数据的图层
 */
@property (nonatomic,strong) CAShapeLayer *limitLayer;

/**
 分时图高度的一半
 */
@property (nonatomic,assign) CGFloat halfTimeLineHeight;
/**
 价格和分时图高比率
 */
@property (nonatomic,assign) CGFloat priceHeightRate;


@end

@implementation StockTimeLineView



- (NSMutableArray*)modelPostionArray
{
    if (!_modelPostionArray)
    {
        _modelPostionArray = [NSMutableArray array];
    }
    return _modelPostionArray;
}

-(instancetype)initWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _timeLineModels = timeLineModels;
    }
    return self;
}
-(void)reDrawWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    _timeLineModels = timeLineModels;
    [self setNeedsDisplay];
}
/**
 开始绘制
 */
- (void)draw
{
    [self drawBoxLayer];//绘制K线的边框
    [self addTimeLayer];//创建分时图时间图层
    [self drawDottedLine];//绘制分时图虚线间隔线
    
    if (self.timeLineModels.count <= 0)return;
    
    [self initConfig];//初始化属性
    [self initModelPostion];//确定每一点的XY坐标
    [self addLimitLayer];//添加限制数据图层
    [self drawLineLayer];//绘制分时线
}
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self draw];
}
/**
 初始化属性
 */
- (void)initConfig
{
    
    StockTimeLineModel *firstModel = self.timeLineModels.firstObject;
    self.priceHeightRate = fabs(([firstModel.MaxPrice floatValue] - [firstModel.MinPrice floatValue]) / (self.height - TimeLineTimeHeight - TimeLineLineWidth * 2));
    self.halfTimeLineHeight = (self.height - TimeLineTimeHeight - TimeLineLineWidth * 2) * 0.5;
    self.lineWidth  = (self.width - TimeLineLeftMargin - TimeLineRightMargin )/TimeLineTimesCount;

}
/**
 确定没一点的XY坐标
 */
- (void)initModelPostion
{
    
    _modelPostionArray = [NSMutableArray array];
    StockTimeLineModel *firstModel = self.timeLineModels.firstObject;
    CGFloat positivePriceChange;
    CGFloat priceChange;
    CGFloat yPostion;
    for (NSInteger i = 0;i<_timeLineModels.count;i++)
    {
        StockTimeLineModel *model = [_timeLineModels objectAtIndex:i];
        CGFloat xPostion = self.lineWidth*i + TimeLineLeftMargin + TimeLineBoxLineWidth;
        //获取当前价格和第一个价格之间的差值
        priceChange = [[[NSString stringWithFormat:@"%@" , model.lastPirce] pz_stringNumberBySubtracting:[NSString stringWithFormat:@"%@" , firstModel.firstPrice]] floatValue];
        positivePriceChange = fabs(priceChange);
        
        //获取这个差价在分时图上所占的高度
        CGFloat priceChangeHeight = positivePriceChange / self.priceHeightRate ;
        
        if (priceChange < 0) {
            yPostion = self.halfTimeLineHeight + priceChangeHeight;
        }else{
            yPostion = self.halfTimeLineHeight - priceChangeHeight;
        }
        
        StockLinePointModel *postitionModel = [StockLinePointModel initPositon:xPostion yPosition:yPostion color:[UIColor redColor]];
        [_modelPostionArray addObject:postitionModel];
    }
}
/**
 添加限制数据图层
 */
-(void)addLimitLayer
{
    self.limitLayer = [CAShapeLayer layer];
    self.limitLayer.contentsScale = [UIScreen mainScreen].scale;
    self.limitLayer.strokeColor = [UIColor clearColor].CGColor;
    self.limitLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:self.limitLayer];
    //这些限制属性放到第一个模型当中
    StockTimeLineModel *model = self.timeLineModels.firstObject;
    //最高价
    CATextLayer *maxPriceLabyer = [self getTextLayer];
    maxPriceLabyer.string = [NSString stringWithFormat:@"%@" , model.MaxPrice];
    maxPriceLabyer.frame = CGRectMake(TimeLineLeftMargin + TimeLineLineWidth, 0, 60, TimeLineTimeHeight);
    maxPriceLabyer.foregroundColor = [UIColor Stock_PriceUpColor].CGColor;
    maxPriceLabyer.alignmentMode = kCAAlignmentLeft;
    [self.limitLayer addSublayer:maxPriceLabyer];
    
    //最低价
    CATextLayer *minPriceLabyer = [self getTextLayer];
    minPriceLabyer.string = [NSString stringWithFormat:@"%@" , model.MinPrice];
    minPriceLabyer.frame = CGRectMake(TimeLineLeftMargin + TimeLineLineWidth, self.height - TimeLineTimeHeight * 2, 60, TimeLineTimeHeight);
    minPriceLabyer.foregroundColor = [UIColor Stock_PriceDownColor].CGColor;
    minPriceLabyer.alignmentMode = kCAAlignmentLeft;
    [self.limitLayer addSublayer:minPriceLabyer];
    
    //第一个价格
    CATextLayer *firstPriceLabyer = [self getTextLayer];
    firstPriceLabyer.string = [NSString stringWithFormat:@"%@" , model.firstPrice];
    firstPriceLabyer.frame = CGRectMake(TimeLineLeftMargin + TimeLineLineWidth, (self.height - TimeLineTimeHeight) * 0.5, 60, TimeLineTimeHeight);
    firstPriceLabyer.foregroundColor = [UIColor Stock_TextColor].CGColor;
    firstPriceLabyer.alignmentMode = kCAAlignmentLeft;
    [self.limitLayer addSublayer:firstPriceLabyer];
    
    //最高涨幅
    CATextLayer *maxUpLabyer = [self getTextLayer];
    maxUpLabyer.string = [NSString stringWithFormat:@"%@%@" , model.MaxUp , @"%"];
    maxUpLabyer.frame = CGRectMake(self.width - TimeLineLineWidth - TimeLineRightMargin - 60, 0, 60, TimeLineTimeHeight);
    maxUpLabyer.foregroundColor = [UIColor Stock_PriceUpColor].CGColor;
    maxUpLabyer.alignmentMode = kCAAlignmentRight;
    [self.limitLayer addSublayer:maxUpLabyer];
    
    //最高跌幅
    CATextLayer *maxDownLabyer = [self getTextLayer];
    maxDownLabyer.string = [NSString stringWithFormat:@"%@%@" , model.MaxDown , @"%"];
    maxDownLabyer.frame = CGRectMake(self.width - TimeLineLineWidth - TimeLineRightMargin - 60, self.height - TimeLineTimeHeight * 2, 60, TimeLineTimeHeight);
    maxDownLabyer.foregroundColor = [UIColor Stock_PriceDownColor].CGColor;
    maxDownLabyer.alignmentMode = kCAAlignmentRight;
    [self.limitLayer addSublayer:maxDownLabyer];
}
/**
 创建分时图时间图层
 */
- (void)addTimeLayer
{
    self.timeLayer = [CAShapeLayer layer];
    self.timeLayer.contentsScale = [UIScreen mainScreen].scale;
    self.timeLayer.strokeColor = [UIColor clearColor].CGColor;
    self.timeLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:self.timeLayer];
    NSArray *array = @[@"09:30" , @"11:30/13:00" , @"15:00"];//分时图默认显示三个时间点
    for (NSInteger i = 0;i<3;i++)
    {
        CGFloat XMargin = (self.width - TimeLineLeftMargin - TimeLineRightMargin) / 3;
        CGFloat x = XMargin*i + TimeLineLeftMargin;
        CATextLayer *layer = [self getTextLayer];
        layer.string = array[i];
        layer.position = CGPointMake(x,self.height - TimeLineTimeHeight/2);
        layer.frame = CGRectMake(x, self.height - TimeLineTimeHeight, XMargin, TimeLineTimeHeight);
        if (i == 0) {
            layer.alignmentMode = kCAAlignmentLeft;
        }
        if (i == 2) {
            layer.alignmentMode = kCAAlignmentRight;
        }
        [self.timeLayer addSublayer:layer];
    }
}

/**
 绘制分时图虚线间隔线
 */
-(void)drawDottedLine
{
    for (NSInteger i = 1; i<3 ;i++)
    {
        CGFloat y = (self.height - TimeLineTimeHeight) /3*(i);
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.lineWidth = TimeLineLineWidth;
        layer.strokeColor = [UIColor Stock_TimeBackLineColor].CGColor;
        [layer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1],nil]];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(TimeLineLeftMargin,y)];
        [path addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,y)];
        layer.path = path.CGPath;
        [self.layer addSublayer:layer];
    }
    
    for (NSInteger i = 1;i < 3;i++)
    {
        CGFloat x = self.width/3*(i);
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.lineWidth = TimeLineLineWidth;
        layer.strokeColor = [UIColor Stock_TimeBackLineColor].CGColor;
        [layer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:1],nil]];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(x,0)];
        [path addLineToPoint:CGPointMake(x,self.height - TimeLineTimeHeight)];
        layer.path = path.CGPath;
        [self.layer addSublayer:layer];
    }
}
/**
 绘制分时线
 */
- (void)drawLineLayer
{
    UIBezierPath *path = [UIBezierPath drawLine:self.modelPostionArray];
    self.lineChartLayer = [CAShapeLayer layer];
    self.lineChartLayer.path = path.CGPath;
    self.lineChartLayer.strokeColor = [UIColor Stock_TimeLineColor].CGColor;
    self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    
    self.lineChartLayer.lineWidth = TimeLineLineWidth;
    self.lineChartLayer.lineCap = kCALineCapRound;
    self.lineChartLayer.lineJoin = kCALineJoinRound;
    self.lineChartLayer.contentsScale = [UIScreen mainScreen].scale;
    [self.layer addSublayer:self.lineChartLayer];
    StockLinePointModel *lastPoint = _modelPostionArray.lastObject;
    //设置分时线的初始点和终点
    [path addLineToPoint:CGPointMake(lastPoint.xPosition,self.height - self.topMargin - TimeLineTimeHeight)];
    [path addLineToPoint:CGPointMake(self.leftMargin, self.height - self.topMargin - TimeLineTimeHeight)];
    path.lineWidth = 0;
    [[UIColor Stock_TimeLineBackColor] setFill];
    [path fill];
    [path stroke];
    [path closePath];
    //绘制闪烁的圆点
    [self startRoundAnimation];
}

/**
 绘制边框图层
 */
- (void)drawBoxLayer
{
    //创建边框图层
    self.boxLayer = [CAShapeLayer layer];
    self.boxLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
    self.boxLayer.contentsScale = [UIScreen mainScreen].scale;
    self.boxLayer.strokeColor = [UIColor clearColor].CGColor;
    self.boxLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:self.boxLayer];
    
    //边框图层
    //左
    CAShapeLayer *leftLayer = [self getAxispLayer];
    leftLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *leftPath = [UIBezierPath bezierPath];
    [leftPath moveToPoint:CGPointMake(TimeLineLeftMargin,0)];
    [leftPath addLineToPoint:CGPointMake(TimeLineLeftMargin, self.height - self.bottomMargin - TimeLineTimeHeight)];
    leftLayer.path = leftPath.CGPath;
    [self.boxLayer addSublayer:leftLayer];
    //右
    CAShapeLayer *rightLayer = [self getAxispLayer];
    rightLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *rightPath = [UIBezierPath bezierPath];
    [rightPath moveToPoint:CGPointMake(self.width - TimeLineRightMargin,0)];
    [rightPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin, self.height - self.bottomMargin - TimeLineTimeHeight)];
    rightLayer.path = rightPath.CGPath;
    [self.boxLayer addSublayer:rightLayer];
    //上
    CAShapeLayer *topLayer = [self getAxispLayer];
    topLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *topPath = [UIBezierPath bezierPath];
    [topPath moveToPoint:CGPointMake(TimeLineLeftMargin,0)];
    [topPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin, 0)];
    topLayer.path = topPath.CGPath;
    [self.boxLayer addSublayer:topLayer];
    //下
    CAShapeLayer *bottomLayer = [self getAxispLayer];
    bottomLayer.lineWidth = TimeLineBoxLineWidth * 0.5;
    UIBezierPath *bottomPath = [UIBezierPath bezierPath];
    [bottomPath moveToPoint:CGPointMake(TimeLineLeftMargin,self.height - self.bottomMargin - TimeLineTimeHeight)];
    [bottomPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,self.height - self.bottomMargin - TimeLineTimeHeight)];
    bottomLayer.path = bottomPath.CGPath;
    [self.boxLayer addSublayer:bottomLayer];
}

/**
 绘制闪烁的圆点
 */
- (void)startRoundAnimation
{
    StockLinePointModel *nextPoint = [_modelPostionArray lastObject];//获取点模型里面最后一个点的坐标
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(nextPoint.xPosition, nextPoint.yPosition) radius:cycleRate startAngle:0 endAngle:2*M_PI clockwise:YES];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.fillColor = [UIColor Stcok_TimeCycleFillColor].CGColor;
    [self.layer addSublayer:layer];
    
    NSInteger pulsingCount = 1;
    double animationDuration = 2;
    CALayer * animationLayer = [CALayer layer];
    for (int i = 0; i < pulsingCount; i++) {
        CALayer * pulsingLayer = [CALayer layer];
        pulsingLayer.frame = CGRectMake(nextPoint.xPosition-cycleRate,nextPoint.yPosition - cycleRate, 10, 10);
        pulsingLayer.borderColor = [UIColor Stcok_TimeCycleFillColor].CGColor;
        pulsingLayer.borderWidth = 1;
        pulsingLayer.cornerRadius = cycleRate;
        CAMediaTimingFunction * defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
        CAAnimationGroup * animationGroup = [CAAnimationGroup animation];
        animationGroup.fillMode = kCAFillModeBackwards;
        animationGroup.beginTime = CACurrentMediaTime() + (double)i * animationDuration / (double)pulsingCount;
        animationGroup.duration = animationDuration;
        animationGroup.repeatCount = HUGE;
        animationGroup.timingFunction = defaultCurve;
        
        CABasicAnimation * scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        scaleAnimation.fromValue = @1;
        scaleAnimation.toValue = @2.2;//放大倍数
        
        CAKeyframeAnimation * opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
        opacityAnimation.values = @[@1, @0.9, @0.8, @0.7, @0.6, @0.5, @0.4, @0.3, @0.2, @0.1, @0];
        opacityAnimation.keyTimes = @[@0, @0.1, @0.2, @0.3, @0.4, @0.5, @0.6, @0.7, @0.8, @0.9, @1];
        animationGroup.animations = @[scaleAnimation, opacityAnimation];
        [pulsingLayer addAnimation:animationGroup forKey:@"plulsing"];
        [animationLayer addSublayer:pulsingLayer];
    }
    [self.layer addSublayer:animationLayer];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(drawGesturePressLine)]) {
        [self.delegate drawGesturePressLine];
    }
}

/**
 获取长按时的坐标点
 */
- (CGPoint)getLongPressModelPostionWithXPostion:(CGFloat)xPostion
{
    //整体遍历一下，看当前的手势点在不在当前数据范围内
    for (NSInteger i = 0; i<self.modelPostionArray.count; i++) {
        StockLinePointModel *model = self.modelPostionArray[i];
        CGFloat minX = fabs(model.xPosition - TimeLineLineWidth);
        CGFloat maxX = model.xPosition + TimeLineLineWidth;
        
        if (xPostion - TimeLineLeftMargin>= minX && xPostion - TimeLineRightMargin  < maxX)
        {
            _curentModelIndex = i;
            return CGPointMake(model.xPosition , model.yPosition);
        }
    }
    //是不是最后一条数据
    StockLinePointModel *lastPoint = _modelPostionArray.lastObject;
    if (xPostion >= lastPoint.xPosition)
    {
        _curentModelIndex = _modelPostionArray.count - 1;
        return CGPointMake(lastPoint.xPosition, lastPoint.yPosition);
    }
    //是不是第一条数据
    StockLinePointModel *firstPoint = _modelPostionArray.firstObject;
    if (fabs(xPostion - TimeLineLeftMargin)  <= firstPoint.xPosition)
    {
        _curentModelIndex = 0;
        return CGPointMake(firstPoint.xPosition, firstPoint.yPosition);
    }
    return CGPointZero;
}

- (CGPoint)getLastModelPostion
{
    if (_modelPostionArray.count>0)
    {
        StockLinePointModel *lastPoint = _modelPostionArray.lastObject;
        return CGPointMake(lastPoint.xPosition, lastPoint.yPosition);
    }
    return CGPointZero;
}

-(StockTimeLineModel *)getLongPressModel
{
    StockTimeLineModel *model = _timeLineModels[_curentModelIndex];
    
    return model;
}

/**
 创建边框图层
 */
- (CAShapeLayer*)getAxispLayer
{
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.strokeColor = [UIColor Stock_BoxColor].CGColor;
    layer.fillColor = [[UIColor clearColor] CGColor];
    layer.contentsScale = [UIScreen mainScreen].scale;
    return layer;
}

/**
 床架文本图层
 */
- (CATextLayer*)getTextLayer
{
    CATextLayer *layer = [CATextLayer layer];
    layer.contentsScale = [UIScreen mainScreen].scale;
    layer.fontSize = font12ScreenWRate * LKScreenW;
    layer.alignmentMode = kCAAlignmentCenter;
    layer.foregroundColor =
    [UIColor Stock_TextColor].CGColor;
    return layer;
}

/**
 计算一个字段的宽高
 */
- (CGRect)rectOfNSString:(NSString *)string attribute:(NSDictionary *)attribute
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 0)
                                       options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil];
    return rect;
}


@end

